<template>
  <el-container class="cc">
    <el-main class="content-section">
      <div class="top-header">
        <h2>医生管理</h2>
        <div class="toolbar">
          <el-button type="primary" @click="goToAddDoctorPage">添加医生</el-button>
          <!-- <el-button type="primary" @click="dialogVisible = true">添加医生</el-button> -->
        </div>
      </div>

      <div class="search-export-header">
        <!-- <div class="search-bar">
          <el-input v-model="search.name" placeholder="搜索姓名" class="search-item"></el-input>
          <el-input v-model="search.hospital" placeholder="搜索医院" class="search-item"></el-input>
          <el-input v-model="search.department" placeholder="搜索科室" class="search-item"></el-input>
          <el-select v-model="search.status" placeholder="账号状态" class="search-item">
            <el-option label="已启用" value="已启用"></el-option>
            <el-option label="已停用" value="已停用"></el-option>
            <el-option label="未启用" value="未启用"></el-option>
          </el-select>
          <el-button type="primary" @click="searchDoctors(search)">搜索</el-button>
          <el-button type="primary" @click="fetchDoctors">搜索全部</el-button>
        </div> -->
        <div class="export-btn">
          <el-button type="primary" @click="tosearchDoctors">搜索</el-button>
          <el-button type="success" @click="exportToExcel">导出</el-button>
        </div>
        
      </div>

      <el-scrollbar style="height: calc(100vh - 200px);">
        <el-table :data="filteredDoctors" style="width: 100%">
          <el-table-column prop="name" label="姓名" width="100"></el-table-column>
          <el-table-column prop="sex" label="性别" width="80"></el-table-column>
          <el-table-column prop="phone" label="电话" width="150"></el-table-column>
          <el-table-column prop="hospital" label="医院"></el-table-column>
          <el-table-column prop="professor" label="职称"></el-table-column>
          <el-table-column prop="department" label="科室"></el-table-column>
          <el-table-column prop="year" label="年限"></el-table-column>
          <el-table-column prop="role" label="级别"></el-table-column>
          <el-table-column prop="type" label="特权"></el-table-column>
          <el-table-column prop="status" label="账号状态"></el-table-column>
          <el-table-column prop="date" label="创建时间"></el-table-column>
          <el-table-column label="操作" width="200">
            <template v-slot="scope">
              <div class="action-buttons">
                <el-button type="text" size="small" @click="editDoctor(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="actDoctor(scope.row)">启用</el-button>
                <el-button type="text" size="small" @click="disableDoctor(scope.row)">停用</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-select v-model="pageSize" @change="handlePageSizeChange" placeholder="每页显示条数">
            <el-option label="10条/页" :value="10"></el-option>
            <el-option label="20条/页" :value="20"></el-option>
            <el-option label="30条/页" :value="30"></el-option>
            <el-option label="40条/页" :value="40"></el-option>
          </el-select>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-scrollbar>
    </el-main>
  </el-container>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="500px"
    @closed="resetForm" 
  >
    <el-form :model="currentDoctor" :rules="rules" ref="doctorForm" label-width="80px">
      <el-form-item label="姓名">
        <el-input v-model="currentDoctor.name"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-input v-model="currentDoctor.sex"></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="currentDoctor.phone"></el-input>
      </el-form-item>
      <el-form-item label="医院">
        <el-input v-model="currentDoctor.hospital"></el-input>
      </el-form-item>
      <el-form-item label="职称">
        <el-input v-model="currentDoctor.professor"></el-input>
      </el-form-item>
      <el-form-item label="科室">
        <el-input v-model="currentDoctor.department"></el-input>
      </el-form-item>
      <el-form-item label="年限">
        <el-input v-model.number="currentDoctor.year"></el-input>
      </el-form-item>
      <el-form-item label="级别">
        <el-input v-model="currentDoctor.role"></el-input>
      </el-form-item>
      <el-form-item label="特权">
        <el-input v-model="currentDoctor.type"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit(currentDoctor)">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
const dialogTitle = ref('医生信息');
import { useRouter } from 'vue-router';
import { ref, computed,watch } from 'vue';
import axios from 'axios';
import { addDoctorApi } from '@/api/api';
import { ElMessage } from 'element-plus';
import { uppdateDoctorApi ,searchDoctorApi } from '@/api/api';
import * as XLSX from 'xlsx';
interface Doctor {
  id: number;
  name: string;
  sex: string;
  phone: string;
  hospital: string;
  professor: string;
  department: string;
  year: number;
  role: string;
  type: string;
  avatar: string;
  pic: string;
  coin: number;
  descp: string | null;
  status: string | null;
  date?: string;
}

const dialogVisible = ref(false)
const selectedMenuItem = ref('doctor');
const router = useRouter();
const currentDoctor = ref<Doctor>({
  id: 0,
  name: '',
  sex: '',
  phone: '',
  hospital: '',
  professor: '',
  department: '',
  year: 0,
  role: '',
  type: '',
  avatar: '',
  pic: '',
  coin: 0,
  descp: null,
  status: null,
  date: ''
});


const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  hospital: [{ required: true, message: '请输入医院', trigger: 'blur' }],
  professor: [{ required: true, message: '请输入职称', trigger: 'blur' }],
  department: [{ required: true, message: '请输入科室', trigger: 'blur' }],
  year: [{ required: true, type: 'number', message: '请输入年限', trigger: 'blur' }],
  role: [{ required: true, message: '请输入级别', trigger: 'blur' }],
  type: [{ required: true, message: '请输入特权', trigger: 'blur' }]
};

const search = ref({
  name: '',
  hospital: '',
  status: '',
  department:''
});

const doctors = ref<Doctor[]>([]);
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);

const axiosInstance = axios.create({});

// 请求拦截器，在请求前执行
axiosInstance.interceptors.request.use((config) => {
  // 每次请求添加 Authorization 到请求头中
  const user = JSON.parse(localStorage.getItem('sysuser') as string);
  if (user && user.jwt) {
    config.headers.Authorization = user.jwt;
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});
const fetchDoctors = async (page = 1) => {
  // if()
  try {
    const response = await axiosInstance.get(`http://localhost:8080/doctormanage/page`, {
      params: {
        current: page,
        size: pageSize.value
      }
    });
    const responseData = response.data.data;
    console.log(response.data.data)
    if (response.data.code === 200) {
      doctors.value = responseData.records;
      total.value = responseData.total;
    } else {
      console.error('Failed to fetch doctors - Response code:', response.data.code);
    }
  } catch (error) {
    console.error('Failed to fetch doctors:', error);
  }
};

fetchDoctors();

const filteredDoctors = computed(() => {
  return doctors.value; // 直接返回原始的医生列表
});


async function searchDoctors(search){
  console.log(search)
  try {
    const response = await searchDoctorApi(search);
    
    // 测试
    console.log(response.data); // 访问 data
    console.log(response.code); // 访问 code

    // 当后端返回200表示成功
    if (response.code === 200) {
      ElMessage({
        message: '查询成功',
        type: 'success',
        plain: true,
      });
      filteredDoctors.value = response.data
    } else {
      ElMessage({
        message: response.msg,
        type: 'error',
        plain: true,
        duration: 1500,
      });
    }
  } catch (error) {
    // 当出现前端异常时, 也应该给出合理提示
    ElMessage({
      message: '修改失败',
      type: 'error',
      plain: true,
      duration: 1500,
    });
  }
  // 触发重新计算filteredDoctors
};

const exportToExcel = () => {
  // 修改表头
  const dataWithCustomHeaders = doctors.value.map(doctor => ({
    姓名: doctor.name,
    性别: doctor.sex,
    电话: doctor.phone,
    医院: doctor.hospital,
    职称: doctor.professor,
    科室: doctor.department,
    年限: doctor.year,
    级别: doctor.role,
    特权: doctor.type,
    状态: doctor.status,
    创建日期: doctor.date
  }));

  // 创建工作表
  const ws = XLSX.utils.json_to_sheet(dataWithCustomHeaders);

  // 创建工作簿
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Doctors');

  // 生成 Excel 文件并触发下载
  XLSX.writeFile(wb, 'doctors.xlsx');
};

const tosearchDoctors = () => {
  router.push('search')
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchDoctors(page);
};

const handlePageSizeChange = (size) => {
  pageSize.value = size;
  fetchDoctors(currentPage.value);
};
const resetForm = () => {
  currentDoctor.value = {
    id: 0,
    name: '',
    sex: '',
    phone: '',
    hospital: '',
    professor: '',
    department: '',
    year: 0,
    role: '',
    type: '',
    avatar: '',
    pic: '',
    coin: 0,
    descp: null,
    status: null,
    date: ''
  };
};

const logout = () => {
  // 处理登出逻辑
};
async function actDoctor(doctor){
  // 停用医生账号的逻辑
  if (doctor.status == '已启用') {
      ElMessage({
        message: '账号已启用，无需修改',
        type: 'error',
        plain: true,
        duration: 1000
        
      })
      return
    } 
  doctor.status='已启用'
  try {
    const response = await uppdateDoctorApi(doctor);
    // 测试
    console.log(response.data); // 访问 data
    console.log(response.code); // 访问 code
    if (response.code === 200) {
      ElMessage({
        message: '启用成功',
        type: 'success',
        plain: true,
        duration: 1000
        
      })
    } else {
      // 非200时, 提示出后端返回的业务异常信息, 例如: 用户名或密码不正确
      ElMessage({
        message: response.msg,
        type: 'error',
        plain: true,
        duration: 1500
      })
    }
  } catch (error) {
    // 当出现前端异常时, 也应该给出合理提示
    ElMessage({
      message: '启用失败:' + error,
      type: 'error',
      plain: true,
      duration: 1500
    })
  }
  
};
const isEditMode = ref(false);
const editDoctor = (doctor) => {
  dialogTitle.value = '编辑医生';
  currentDoctor.value = { ...doctor };
  dialogVisible.value=true
  isEditMode.value=false
  // 编辑医生信息的逻辑
  
  
};
const goToAddDoctorPage = () => {
  // 重置 currentDoctor 对象
  resetForm();
  dialogTitle.value = '添加新医生';
  dialogVisible.value = true;
  isEditMode.value = true;
  currentDoctor;
  console.log(currentDoctor)
};

async function submit(currentDoctor) {
  if(isEditMode.value){
    try {
    const response = await addDoctorApi(currentDoctor);
    
    // 测试
    console.log(response.data); // 访问 data
    console.log(response.code); // 访问 code

    // 当后端返回200表示成功
    if (response.code === 200) {
      ElMessage({
        message: '添加成功',
        type: 'success',
        plain: true,
      });
      // router.push({ name: 'doctor' });
      dialogVisible.value = false
      const currentRoute = router.currentRoute.value;
          router.replace({ path: '/index', query: { t: Date.now() } }).then(() => {
            router.replace(currentRoute.fullPath);
          });
    } else {
      ElMessage({
        message: response.msg,
        type: 'error',
        plain: true,
        duration: 1500,
      });
    }
  } catch (error) {
    // 当出现前端异常时, 也应该给出合理提示
    ElMessage({
      message: '添加失败',
      type: 'error',
      plain: true,
      duration: 1500,
    });
  }
  }else{
    try {
    const response = await uppdateDoctorApi(currentDoctor);
    
    // 测试
    console.log(currentDoctor.name+'11111')
    console.log(response.data); // 访问 data
    console.log(response.code); // 访问 code

    // 当后端返回200表示成功
    if (response.code === 200) {
      ElMessage({
        message: '修改成功',
        type: 'success',
        plain: true,
      });
      router.push({ name: 'doctor' });
      dialogVisible.value = false
      const currentRoute = router.currentRoute.value;
          router.replace({ path: '/index', query: { t: Date.now() } }).then(() => {
            router.replace(currentRoute.fullPath);
          });
    } else {
      ElMessage({
        message: response.msg,
        type: 'error',
        plain: true,
        duration: 1500,
      });
    }
  } catch (error) {
    // 当出现前端异常时, 也应该给出合理提示
    ElMessage({
      message: '修改失败',
      type: 'error',
      plain: true,
      duration: 1500,
    });
  }
  }
  
};

async function disableDoctor(doctor){
  // 停用医生账号的逻辑
  if (doctor.status == '已停用' ||  doctor.status == null || doctor.status == '未启用') {
      ElMessage({
        message: '账号已停用或未启用，禁止修改',
        type: 'error',
        plain: true,
        duration: 1000
        
      })
      return
    } 
  doctor.status='已停用'
  try {
    const response = await uppdateDoctorApi(doctor);
    // 测试
    console.log(response.data); // 访问 data
    console.log(response.code); // 访问 code
    // 当后端返回200表示登录成功
    if (response.code === 200) {
      ElMessage({
        message: '修改成功',
        type: 'success',
        plain: true,
        duration: 1000
        
      })
    } else {
      // 非200时, 提示出后端返回的业务异常信息, 例如: 用户名或密码不正确
      ElMessage({
        message: response.msg,
        type: 'error',
        plain: true,
        duration: 1500
      })
    }
  } catch (error) {
    // 当出现前端异常时, 也应该给出合理提示
    ElMessage({
      message: '修改失败:' + error,
      type: 'error',
      plain: true,
      duration: 1500
    })
  }

  console.log(doctor.id)
  doctor.status="已停用"
  console.log(doctor.status)
};

</script>

<style scoped>
.top-header,
.search-export-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #f2f2f2;
  border-bottom: 1px solid #e2e2e2;
}

.toolbar {
  display: flex;
  align-items: center;
}

.toolbar span {
  margin-right: 20px;
}

.content-section {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
}

.search-bar .search-item {
  margin-right: 10px;
  width: 200px;
}

.export-btn {
  margin-left: auto;
}

.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination-container .el-select {
  width: 120px;
  margin-right: 20px;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
</style>
